import {defineStore} from "pinia";
import {CacheMap, useCache} from "../utils/CacheUtils.ts";
import {ResourceApi} from "../network/api/ResourceApi.ts";
import axios from "axios";
import type {ThirdPartyEmoteCategory} from "../types/Emote.ts";
import type {AvatarBuff, BbsCodeBody, Emote, UiResource} from "../network/types/Resources.ts";

const api = new ResourceApi("/static/res");

// 第三方表情包地址json
const thirdPartyEmoteUrl = "/gitee/AgMonk/nga-common-asset/raw/master/emotes/url.json"

export const useResourceStore = defineStore('ResourceStore', {
    state: () => ({
        cache: new CacheMap<any>(),
        emotes: new Array<Emote>(),
        avatarBuffs: new Array<AvatarBuff>(),
    }),
    actions: {
        bbsCode(force?: boolean): Promise<BbsCodeBody> {
            const key = `bbsCode`
            return useCache(this.cache, key, force || false, () => api.bbsCode().then(res => {
                this.emotes = res.emoteGroups.flatMap(group => group.emotes)

                res.emoteGroups.forEach(group => group.emotes.forEach(emote =>
                    // 替换图片地址前缀
                    emote.url = emote.url.replace('https://img4.nga.178.com', '/static/res')))

                return res
            }), 60 * 60)
        },
        // 查询或修改屏蔽的分组名单
        blockedNames(names?: string[] | undefined): string[] {
            const key = `blockedNames`
            if (names) {
                localStorage.setItem(key, names?.join("\t"))
                return names
            }
            return localStorage.getItem(key)?.split("\t") || []
        },
        // 第三方表情包分类
        thirdPartyEmoteCategory(force?: boolean) {
            const key = `thirdPartyEmoteCategory`
            return useCache(this.cache, key, force || false, async () => {
                const urlRes = await axios.get(thirdPartyEmoteUrl);
                const urls = urlRes.data;
                const result: ThirdPartyEmoteCategory[] = []
                for (const url of urls) {
                    const groupRes = await axios.get(url.replace('https://gitee.com', '/gitee'));
                    result.push(groupRes.data)
                }
                return result
            }, 60 * 60)
        },
        indexForums(force?: boolean): Promise<any> {
            const key = `indexForums`
            return useCache(this.cache, key, force || false, () => api.indexForums(), 60 * 60)
        },
        async uiResource(force?: boolean): Promise<UiResource> {
            const key = `uiResource`
            return useCache(this.cache, key, force || false, () => api.uiResource(), 60 * 60).then(res => {
                this.avatarBuffs = res.avatarBuffs
                return res
            })
        },
    },
})
